import Vue from 'vue'
import VueRouter from 'vue-router'
import Qs from 'qs';
import axios from 'axios';
import ElementUI from 'element-ui'
import Vuex from 'vuex'

import routes from './config/routes'
import store from './config/vuex/store'
import App from './App.vue'

Vue.use(VueRouter)
Vue.use(ElementUI)
Vue.use(Vuex)

axios.defaults.baseURL = '/api';
// axios.defaults.baseURL = 'http://api.007macau.com';
axios.defaults.withCredentials = true;
// axios.defaults.headers['Content-Type'] = 'application/json'
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.headers['token'] = store.getters.userProfile?store.getters.userProfile.token:'0';
axios.defaults.transformRequest = [function(data) {
	//为了避免qs格式化时对内层对象的格式化先把内层的对象转为
	// data.CustData = JSON.stringify(data.CustData);
	//由于使用的form-data传数据所以要格式化
	data = Qs.stringify(data);
	return data;
}];
axios.defaults.transformResponse = [function(data) {
	// TODO 调试可看到所有的请求返回参数，发布时删除，发布时也删除所有的console.log
	// console.log(data);
	// console.log(JSON.parse(data));
	try{
		return JSON.parse(data);
	}catch(e){
		return data;
	}

}];
//POST传参序列化(添加请求拦截器)
// axios.interceptors.request.use((config) => {
// 	//在发送请求之前做某件事
// 	if(config.method === 'post') {
// 		config.data = Qs.stringify(config.data);
// 	}
// 	return config;
// }, (error) => {
// 	console.error('post请求错误参数');
// 	return Promise.reject(error);
// });

// axios.interceptors.response.use(function(response) {
// 	if(response.data.success === false && response.data.error_code === 100) {
// 		store.dispatch('logout');
// 		//		layer.goLogin();
// 	}
// 	return response;
// }, function(error) {
// 	return Promise.reject(error);
// });
axios.defaults.timeout = 5000;

Vue.prototype.$http = axios;

const router = new VueRouter({
	routes,
	mode: 'history',
	scrollBehavior(to, from, savedPosition) {
		return {
			x: 0,
			y: 0
		}
	},
});

router.beforeEach((to, from, next) => {
	next();
});

router.afterEach(route => {
	//	console.log(route.to.title);
});

new Vue({
	el: '#app',
	router,
	store,
	render: (h) => h(App)
});
